import 'package:flutter/material.dart';
import 'package:package_info/package_info.dart';
import 'package:qgchat/common/action/index.dart';
import 'package:qgchat/common/class/db/db.dart';
import 'package:qgchat/common/class/websocket/SocketBuilder.dart';
import 'package:qgchat/common/class/websocket/index.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/apis/common.dart';
import 'package:qgchat/http/apis/user.dart';
import 'package:qgchat/http/models/checkVersionModel.dart';
import 'package:qgchat/http/models/userInfoModel.dart';
import 'package:qgchat/page/live/videoPage/listenTalk/index.dart';
import 'package:qgchat/page/tabBar_page.dart';
import 'package:qgchat/widgets/Zego/ZegoBuilder.dart';
import 'package:qgchat/widgets/bugly/bugly.dart';
import 'package:qgchat/widgets/mobpush/MobPush.dart';
import 'package:qgchat/widgets/updateDialog.dart';
import 'package:qgchat/widgets/wechat/wx.dart';
import 'package:shared_preferences/shared_preferences.dart';

///
/// 权限组件
/// 当本地缓存中有token时去主页
/// 否则去登录页
/// 同时还处理app版本更新等功能
///

class Auth extends StatefulWidget {
  Auth({Key key}) : super(key: key);

  @override
  _AuthState createState() => _AuthState();
}

class _AuthState extends State<Auth> {
  @override
  void initState() {
    super.initState();
    if (mounted) {
      initApp();
      checkUpload();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // floatingActionButton: FloatingActionButton(
      //   onPressed: () {
      //     GiftToast.show(WsAllGiftModel.fromJson(
      //       {
      //         "head": "https://cdn.tangzhijiaowh.cn/810527df7435aedcd659503237e83ef7",
      //         "name": "132267",
      //         "number": 1,
      //         "giftname": "荧光棒",
      //         "icon": "http://video.xczb1.com/FuDNZrMpXepYaopzmQd3mOwxubxi",
      //         "token": "89bcbd184b9d33e02848caf01b8f3540",
      //         "anchor_head": "https://cdn.tangzhijiaowh.cn/b318104da3b09041c7692981d22e9773",
      //         "anchor_name": "啊俊",
      //         "anchor_token": "a34a1d41b5f1eb3cb96e5e5013383393",
      //         "id": 1,
      //       }
      //     ));
      //   },
      // ),
      
      body: Bugly(
        child: Wx(
          child: ZegoBuilder(
            child: SocketBuilder(
              child: FutureBuilder(
                future: lodingApp(),
                builder: (BuildContext context, AsyncSnapshot snapshot) {
                  if (snapshot.hasData) {
                    return MobPush(
                      child: ListenTalk(
                        child: AppBottomBars(),
                      ),
                    );
                  } else {
                    return Container(color: Colors.white);
                  }
                },
              ),
            ),
          ),
        ),
      ),
    );
  }

  // 检测是否需要更新
  checkUpload() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String version = packageInfo.version;
    CheckVersionModel check =
        await CommonApis.checkVersion(version, isIos ? 1 : 0);
    if (check != null && check.update) {
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return UpdateDialog(
            version: version,
            link: '${check.url}',
            tips: '${check.tips}',
            isNotForce: false,
          );
        },
      );
    }
  }

  // 初始化app
  Future lodingApp() async {
    if (Global.prefs != null) {
      return false;
    }
    await lodingPrefs();
    await initAppData();
    return true;
  }

  // 异步加载缓存
  Future lodingPrefs() async {
    Global.prefs = await SharedPreferences.getInstance(); // 初始化缓存
    return Global.prefs;
  }

  // 初始化app功能
  initApp() async {
    Global.prefs = await SharedPreferences.getInstance(); // 初始化缓存
    if (cache.getString("token") == null) {
      return;
    }
    UserInfoModel userInfo = await UserApis.myInfo();

    Global.db = Db(userInfo);
    await Global.db.openDb();
    Global.db.queryMyAll(ctx: context);

    if (Global.ws == null) {
      Global.ws = WebSocket(userInfo);
    }

    // 登录日志
    CommonAction.deviceDetailInfo().then((device) async {
      UserApis.loginLog(device.toJson());
    });
  }

  /// 初始化app数据
  Future initAppData() async {
    if (cache.getString('token') == null) {
      return false;
    }
    await state(context, "user").userInfo();
    state(context, "user").alipayInfo();
  }
}
